package com.bjpowernode.boss.mvc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjpowernode.boss.common.enums.PublicStatus;
import com.bjpowernode.boss.common.enums.ResponseCode;
import com.bjpowernode.boss.common.exception.BossException;
import com.bjpowernode.boss.common.utils.NumberUtil;
import com.bjpowernode.boss.convert.UserConvert;
import com.bjpowernode.boss.dao.entity.UserAccount;
import com.bjpowernode.boss.dao.entity.UserInfo;
import com.bjpowernode.boss.dao.mapper.UserAccountMapper;
import com.bjpowernode.boss.dao.mapper.UserInfoMapper;
import com.bjpowernode.boss.mvc.models.form.user.UserEditForm;
import com.bjpowernode.boss.mvc.models.vo.user.UserInfoVo;
import com.bjpowernode.boss.mvc.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author yu
 * @date 2024/7/9  23:51
 */

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserConvert userConvert ;

    @Resource
    private UserInfoMapper userInfoMapper ;

    @Resource
    private UserAccountMapper userAccountMapper ;

    @Override
    public IPage<UserInfo> pageList(Integer pageNo, Integer pageSize) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>() ;
        wrapper.orderByDesc("create_time") ;

        IPage<UserInfo> userInfoIPage = userInfoMapper.selectPage(Page.of(pageNo, pageSize), wrapper) ;
        return userInfoIPage ;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editUser(UserEditForm userEditForm) {
        int edit = 0 ;
        if (StrUtil.isNotBlank(userEditForm.getId())) { // 编辑
            // 复制属性
            UserInfo userInfo = userConvert.mapUserInfo(userEditForm) ;
            edit = userInfoMapper.updateById(userInfo) ;
        }
        else { // 新增
            // 1. loginName不能重复，所以先从数据查询
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>() ;
            wrapper.eq("login_name", userEditForm.getLoginName()) ;
            UserInfo user = userInfoMapper.selectOne(wrapper);
            if (user != null) { // 登录名称重复
                throw new BossException(ResponseCode.USER_LOGIN_NAME_EXISTS) ;
            }

            // 创建新商户 UserInfo
            UserInfo userInfo = new UserInfo() ;
            userInfo.setId(NumberUtil.getUUID());
            userInfo.setUserNo(NumberUtil.getUserNo());
            userInfo.setLoginName(userEditForm.getLoginName());
            userInfo.setAccountNo(NumberUtil.getAccountNo());
            userInfo.setPhone(userEditForm.getPhone());
            userInfo.setPassword(NumberUtil.getUUID());
            userInfo.setPayPwd(NumberUtil.getUUID());
            userInfo.setShopName(userEditForm.getShopName());
            userInfo.setShopScope(userEditForm.getShopScope());
            userInfo.setUserEmail(userEditForm.getEmail());
            userInfo.setStatus(PublicStatus.DISABLE.name());
            userInfo.setCreateTime(new Date());
            userInfo.setRemark("创建商户");

            edit = userInfoMapper.insert(userInfo) ;

            // 创建Account
            UserAccount account = new UserAccount() ;
            account.setId(NumberUtil.getUUID());
            account.setUserNo(userInfo.getUserNo());
            account.setAccountNo(NumberUtil.getAccountNo());
            account.setBalance(new BigDecimal(0));
            account.setTotalIncome(new BigDecimal(0));
            account.setTotalExpend(new BigDecimal(0));
            account.setStatus(PublicStatus.DISABLE.getMsg());
            account.setRemark("新商户创建资金账号");
            account.setEditTime(new Date());

            userAccountMapper.insert(account) ;
        }

        return edit ;
    }

    @Override
    public UserInfoVo getUserById(String userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId) ;
        return userConvert.mapUserInfoVo(userInfo) ;
    }

    @Override
    public int editStatusById(String userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>() ;
        queryWrapper.eq("id", userId) ;
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        String status = PublicStatus.DISABLE.name().equals(userInfo.getStatus()) ? PublicStatus.ENABLE.name() : PublicStatus.DISABLE.name();


        UpdateWrapper<UserInfo> wrapper = new UpdateWrapper<>() ;

        // 或者使用lambda表达式（MyBatis-Plus 3.x及以上版本）
        wrapper.lambda().eq(UserInfo::getId, userId).set(UserInfo::getStatus, status);
        return userInfoMapper.update(null, wrapper);
    }
}
